<script lang="ts" setup>
import { ref, onMounted } from 'vue'

const currentTimestamp = ref(0)
const currentDateTime = ref('')
const inputTimestamp = ref('')
const inputDateTime = ref('')
const convertedDateTime = ref('')
const convertedTimestamp = ref('')
const errorMessage = ref('')
const isSuccess = ref(false)
const timestampUnit = ref('seconds') // seconds or milliseconds
const dateTimeFormat = ref('YYYY-MM-DD HH:mm:ss')

// 更新当前时间
function updateCurrentTime() {
  const now = new Date()
  currentTimestamp.value = Math.floor(now.getTime() / 1000)
  currentDateTime.value = formatDateTime(now)
}

// 格式化日期时间
function formatDateTime(date: Date): string {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  switch (dateTimeFormat.value) {
    case 'YYYY-MM-DD HH:mm:ss':
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    case 'YYYY/MM/DD HH:mm:ss':
      return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
    case 'MM/DD/YYYY HH:mm:ss':
      return `${month}/${day}/${year} ${hours}:${minutes}:${seconds}`
    case 'DD-MM-YYYY HH:mm:ss':
      return `${day}-${month}-${year} ${hours}:${minutes}:${seconds}`
    case 'ISO':
      return date.toISOString()
    default:
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
}

// 时间戳转日期时间
function timestampToDateTime() {
  try {
    if (!inputTimestamp.value.trim()) {
      errorMessage.value = '请输入时间戳'
      isSuccess.value = false
      return
    }
    
    let timestamp = parseInt(inputTimestamp.value)
    if (isNaN(timestamp)) {
      errorMessage.value = '时间戳格式错误'
      isSuccess.value = false
      return
    }
    
    // 根据单位转换
    if (timestampUnit.value === 'seconds') {
      timestamp = timestamp * 1000
    }
    
    const date = new Date(timestamp)
    if (isNaN(date.getTime())) {
      errorMessage.value = '无效的时间戳'
      isSuccess.value = false
      return
    }
    
    convertedDateTime.value = formatDateTime(date)
    errorMessage.value = '转换成功 ✓'
    isSuccess.value = true
  } catch (error) {
    errorMessage.value = `转换失败: ${(error as Error).message}`
    isSuccess.value = false
  }
}

// 日期时间转时间戳
function dateTimeToTimestamp() {
  try {
    if (!inputDateTime.value.trim()) {
      errorMessage.value = '请输入日期时间'
      isSuccess.value = false
      return
    }
    
    const date = new Date(inputDateTime.value)
    if (isNaN(date.getTime())) {
      errorMessage.value = '日期时间格式错误'
      isSuccess.value = false
      return
    }
    
    let timestamp = date.getTime()
    if (timestampUnit.value === 'seconds') {
      timestamp = Math.floor(timestamp / 1000)
    }
    
    convertedTimestamp.value = timestamp.toString()
    errorMessage.value = '转换成功 ✓'
    isSuccess.value = true
  } catch (error) {
    errorMessage.value = `转换失败: ${(error as Error).message}`
    isSuccess.value = false
  }
}

// 复制到剪贴板
function copyToClipboard(text: string, type: string) {
  if (text) {
    navigator.clipboard.writeText(text).then(() => {
      errorMessage.value = `${type}已复制到剪贴板 ✓`
      isSuccess.value = true
    })
  }
}

// 清空所有
function clearAll() {
  inputTimestamp.value = ''
  inputDateTime.value = ''
  convertedDateTime.value = ''
  convertedTimestamp.value = ''
  errorMessage.value = ''
  isSuccess.value = false
}

// 获取当前时间戳
function getCurrentTimestamp() {
  const now = new Date()
  let timestamp = now.getTime()
  if (timestampUnit.value === 'seconds') {
    timestamp = Math.floor(timestamp / 1000)
  }
  inputTimestamp.value = timestamp.toString()
}

// 获取当前日期时间
function getCurrentDateTime() {
  const now = new Date()
  inputDateTime.value = formatDateTime(now)
}

// 加载示例
function loadSample() {
  const now = new Date()
  inputTimestamp.value = Math.floor(now.getTime() / 1000).toString()
  inputDateTime.value = formatDateTime(now)
}

// 组件挂载时开始更新时间
onMounted(() => {
  updateCurrentTime()
  setInterval(updateCurrentTime, 1000)
})
</script>

<template>
  <div class="timestamp-tool">
    <div class="current-time-section">
      <h3>当前时间</h3>
      <div class="current-time-display">
        <div class="time-item">
          <label>当前时间戳:</label>
          <div class="time-value">
            <span>{{ currentTimestamp }}</span>
            <button class="btn btn-sm" @click="copyToClipboard(currentTimestamp.toString(), '时间戳')">
              📋
            </button>
          </div>
        </div>
        <div class="time-item">
          <label>当前日期时间:</label>
          <div class="time-value">
            <span>{{ currentDateTime }}</span>
            <button class="btn btn-sm" @click="copyToClipboard(currentDateTime, '日期时间')">
              📋
            </button>
          </div>
        </div>
      </div>
    </div>

    <div class="config-section">
      <h3>配置选项</h3>
      <div class="config-grid">
        <div class="config-item">
          <label>时间戳单位:</label>
          <select v-model="timestampUnit" class="config-select">
            <option value="seconds">秒 (Unix时间戳)</option>
            <option value="milliseconds">毫秒 (JavaScript时间戳)</option>
          </select>
        </div>
        <div class="config-item">
          <label>日期时间格式:</label>
          <select v-model="dateTimeFormat" class="config-select">
            <option value="YYYY-MM-DD HH:mm:ss">YYYY-MM-DD HH:mm:ss</option>
            <option value="YYYY/MM/DD HH:mm:ss">YYYY/MM/DD HH:mm:ss</option>
            <option value="MM/DD/YYYY HH:mm:ss">MM/DD/YYYY HH:mm:ss</option>
            <option value="DD-MM-YYYY HH:mm:ss">DD-MM-YYYY HH:mm:ss</option>
            <option value="ISO">ISO 8601</option>
          </select>
        </div>
      </div>
    </div>

    <div class="controls">
      <button class="btn btn-primary" @click="timestampToDateTime">🔄 时间戳转日期</button>
      <button class="btn btn-primary" @click="dateTimeToTimestamp">🔄 日期转时间戳</button>
      <button class="btn btn-info" @click="getCurrentTimestamp">⏰ 获取当前时间戳</button>
      <button class="btn btn-info" @click="getCurrentDateTime">📅 获取当前日期</button>
      <button class="btn btn-warning" @click="loadSample">📝 加载示例</button>
      <button class="btn btn-danger" @click="clearAll">🗑️ 清空</button>
    </div>

    <div class="status" v-if="errorMessage" :class="{ 'error': !isSuccess, 'success': isSuccess }">
      {{ errorMessage }}
    </div>

    <div class="converter-container">
      <div class="converter-section">
        <h3>时间戳转日期时间</h3>
        <div class="input-group">
          <input 
            v-model="inputTimestamp" 
            type="text" 
            class="timestamp-input"
            :placeholder="timestampUnit === 'seconds' ? '输入Unix时间戳 (秒)...' : '输入JavaScript时间戳 (毫秒)...'"
          >
          <button class="btn btn-primary" @click="timestampToDateTime">转换</button>
        </div>
        <div class="result-area">
          <textarea 
            v-model="convertedDateTime" 
            class="result-output"
            placeholder="转换后的日期时间将显示在这里..."
            readonly
          ></textarea>
          <button 
            class="btn btn-success btn-sm" 
            @click="copyToClipboard(convertedDateTime, '日期时间')"
            :disabled="!convertedDateTime"
          >
            📋 复制
          </button>
        </div>
      </div>

      <div class="converter-section">
        <h3>日期时间转时间戳</h3>
        <div class="input-group">
          <input 
            v-model="inputDateTime" 
            type="text" 
            class="datetime-input"
            placeholder="输入日期时间 (如: 2024-01-01 12:00:00)..."
          >
          <button class="btn btn-primary" @click="dateTimeToTimestamp">转换</button>
        </div>
        <div class="result-area">
          <textarea 
            v-model="convertedTimestamp" 
            class="result-output"
            placeholder="转换后的时间戳将显示在这里..."
            readonly
          ></textarea>
          <button 
            class="btn btn-success btn-sm" 
            @click="copyToClipboard(convertedTimestamp, '时间戳')"
            :disabled="!convertedTimestamp"
          >
            📋 复制
          </button>
        </div>
      </div>
    </div>

    <div class="help-section">
      <details>
        <summary>使用说明</summary>
        <div class="help-content">
          <h4>时间戳格式说明:</h4>
          <ul>
            <li><strong>Unix时间戳 (秒):</strong> 从1970年1月1日00:00:00 UTC开始的秒数，如: 1640995200</li>
            <li><strong>JavaScript时间戳 (毫秒):</strong> 从1970年1月1日00:00:00 UTC开始的毫秒数，如: 1640995200000</li>
          </ul>
          <h4>支持的日期时间格式:</h4>
          <ul>
            <li>YYYY-MM-DD HH:mm:ss (如: 2024-01-01 12:00:00)</li>
            <li>YYYY/MM/DD HH:mm:ss (如: 2024/01/01 12:00:00)</li>
            <li>MM/DD/YYYY HH:mm:ss (如: 01/01/2024 12:00:00)</li>
            <li>ISO 8601格式 (如: 2024-01-01T12:00:00.000Z)</li>
          </ul>
        </div>
      </details>
    </div>
  </div>
</template>

<style scoped>
.timestamp-tool {
  width: 100%;
}

.current-time-section {
  margin-bottom: 20px;
  padding: 20px;
  background: rgba(0, 123, 255, 0.1);
  border-radius: 8px;
  border: 1px solid rgba(0, 123, 255, 0.3);
}

.current-time-section h3 {
  margin: 0 0 15px 0;
  color: #007bff;
  font-size: 1.1em;
}

.current-time-display {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.time-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.time-item label {
  color: #ccc;
  font-size: 14px;
  font-weight: 500;
}

.time-value {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 4px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.time-value span {
  flex: 1;
  color: #fff;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
}

.config-section {
  margin-bottom: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.config-section h3 {
  margin: 0 0 15px 0;
  color: #fff;
  font-size: 1.1em;
}

.config-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.config-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.config-item label {
  color: #ccc;
  font-size: 14px;
  font-weight: 500;
}

.config-select {
  padding: 8px 12px;
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  color: #fff;
  font-size: 14px;
  outline: none;
}

.config-select:focus {
  border-color: rgba(255, 255, 255, 0.4);
}

.controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  color: #fff;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

.btn-primary {
  background: #007bff;
}

.btn-primary:hover:not(:disabled) {
  background: #0056b3;
}

.btn-success {
  background: #28a745;
}

.btn-success:hover:not(:disabled) {
  background: #1e7e34;
}

.btn-info {
  background: #17a2b8;
}

.btn-info:hover:not(:disabled) {
  background: #117a8b;
}

.btn-warning {
  background: #ffc107;
  color: #212529;
}

.btn-warning:hover:not(:disabled) {
  background: #e0a800;
}

.btn-danger {
  background: #dc3545;
}

.btn-danger:hover:not(:disabled) {
  background: #c82333;
}

.status {
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 20px;
  font-weight: 500;
}

.status.error {
  background: rgba(220, 53, 69, 0.1);
  color: #dc3545;
  border: 1px solid rgba(220, 53, 69, 0.3);
}

.status.success {
  background: rgba(40, 167, 69, 0.1);
  color: #28a745;
  border: 1px solid rgba(40, 167, 69, 0.3);
}

.converter-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.converter-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.converter-section h3 {
  margin: 0;
  color: #fff;
  font-size: 1.1em;
}

.input-group {
  display: flex;
  gap: 10px;
}

.timestamp-input,
.datetime-input {
  flex: 1;
  padding: 10px 12px;
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  color: #fff;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
  outline: none;
}

.timestamp-input:focus,
.datetime-input:focus {
  border-color: rgba(255, 255, 255, 0.4);
}

.timestamp-input::placeholder,
.datetime-input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.result-area {
  position: relative;
}

.result-output {
  width: 100%;
  height: 100px;
  background: rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  padding: 12px;
  color: #fff;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  outline: none;
}

.result-output::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.result-area .btn {
  position: absolute;
  top: 8px;
  right: 8px;
}

.help-section {
  margin-top: 20px;
}

.help-section details {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.help-section summary {
  padding: 12px 15px;
  cursor: pointer;
  color: #fff;
  font-weight: 500;
  user-select: none;
}

.help-section summary:hover {
  background: rgba(255, 255, 255, 0.05);
}

.help-content {
  padding: 15px;
  color: #ccc;
}

.help-content h4 {
  margin: 0 0 10px 0;
  color: #fff;
  font-size: 1em;
}

.help-content ul {
  margin: 0 0 15px 0;
  padding-left: 20px;
}

.help-content li {
  margin-bottom: 5px;
  line-height: 1.4;
}

.help-content strong {
  color: #fff;
}

@media (max-width: 768px) {
  .current-time-display {
    grid-template-columns: 1fr;
  }
  
  .config-grid {
    grid-template-columns: 1fr;
  }
  
  .converter-container {
    grid-template-columns: 1fr;
  }
  
  .controls {
    justify-content: center;
  }
  
  .input-group {
    flex-direction: column;
  }
}
</style>